package edu.ybu.manage.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.ybu.manage.pojo.Goods;
import edu.ybu.manage.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @RequestMapping("selectAll")
    public Map<String,Object> selectAll(){
        List<Goods> goodsList = goodsService.selectAll();
        System.out.println(goodsList);
        Map<String,Object> res = new HashMap<>();
        res.put("code",0);
        res.put("msg","");
        res.put("data",goodsList);
        return res;
    }

    @RequestMapping("/insertGoods")
    public Integer insertGoods(String json){
//        System.out.println(json);
        ObjectMapper objectMapper = new ObjectMapper();
        Goods goods = null;
        try {
            goods = objectMapper.readValue(json, Goods.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println(goods);

        return goodsService.insertGoods(goods);
    }

    @RequestMapping("/updateById")
    public Integer updateById(String json){
        ObjectMapper objectMapper = new ObjectMapper();
        Goods goods = null;
        try {
            goods = objectMapper.readValue(json, Goods.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return goodsService.updateProductById(goods);
    }
    @RequestMapping("/deleteGoods")
    public Integer deleteGoods(String json){
        ObjectMapper objectMapper = new ObjectMapper();
        Goods goods = null;
        try {
            goods = objectMapper.readValue(json, Goods.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return goodsService.deleteProduct(goods);
    }
}
